<template>
  <div>
    <div class="operation">
      <el-link ref="template" :underline="false" :href="tplUrl" type="primary">
        <el-button type="text" @click="downloadTpl">1.下载模板</el-button>
      </el-link>
      <fileUpload v-model="filePath" class="mt10">
        <el-button size="small" plain>2. 选择文件</el-button>
      </fileUpload>
      <div class="mt10 mb10">
        <el-button size="small" :disabled="previewIsDisable" @click="uploadFileView">
          3. 预览数据
        </el-button>
        <el-button
          size="small"
          type="primary"
          :disabled="importIsDisable"
          @click="handleImportData()"
        >
          4. 导入数据
        </el-button>
      </div>
    </div>

    <vxe-grid border stripe height="600" :columns="tableColumn" :data.sync="tableData"></vxe-grid>
  </div>
</template>
<script>
import { tableColumn, interfaces } from './tableColumn-interfaces'
import fileUpload from '@/views/components/fileUpload.vue'
export default {
  name: 'ImportFile',
  components: { fileUpload },
  props: {
    type: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      tplUrl: '', // 模板地址
      filePath: '', // 上传成功后的地址
      previewIsDisable: true, // 预览按钮
      importIsDisable: true, // 导入按钮
      tableColumn: [], // 表格列
      tableData: [], // 表格数据
      // 预览时候生成的随机编码，会将这个编码和导入的内容以key-value形式保存在缓存里。执行导入时直接根据这个编码从缓存中取出导入内容
      importCode: ''
    }
  },
  watch: {
    filePath(val) {
      this.previewIsDisable = val !== '' ? false : true
      if (val === '') {
        this.tableData = []
        this.importIsDisable = true
      }
    }
  },
  created() {
    this.tableColumn = tableColumn[this.type]
    this.tplUrl = interfaces[this.type].dlTpl()
  },

  methods: {
    // 给<el-link>中的href进行赋值方法
    downloadTpl() {
      const dom = this.$refs.template // 获取html的el-link标签
      dom.href = this.tplUrl // 赋值到href属性
    },
    // 预览
    uploadFileView() {
      interfaces[this.type].previewFile({ filePath: this.filePath }, (result) => {
        this.tableData = result.data
        this.importIsDisable = false
        this.importCode = result.data[0].importCode
      })
    },
    // 数据入库
    handleImportData() {
      const rLoading = this.openLoading({
        text: '导入中...',
        duration: 'n'
      })
      interfaces[this.type].importData({ importCode: this.importCode }, (result) => {
        rLoading.close()
        this.$emit('importFileSuccess', result)
      })
    }
  }
}
</script>
<style scoped>
.operation {
  margin-left: 60px;
}
.mt10 {
  margin-top: 20px;
}
.mb10 {
  margin-bottom: 20px;
}
</style>
